<template>
   <div class="detailPage2-container">
       <div class="d-c-top">
           <div class="d-c-form">
               <span class="form-label required">表单名称</span>
               <el-input
                   v-model="form.formName"
                   class="form-input"
                   placeholder="表单名称"
                   clearable
               ></el-input>
           </div>
           <div class="d-c-form">
               <span class="form-label">表单描述</span>
               <el-input
                   v-model="form.formDescription"
                   class="form-input"
                   placeholder="表单描述"
                   clearable
               ></el-input>
           </div>
           <div class="d-c-form" v-if="_isOperation">
               <span class="form-label required">选择数据对应镇</span>
               <el-cascader
                   class="pbb__search-input"
                   v-model="form.cityCode"
                   :options="options"
                   :props="props"
                   :placeholder="form.cityLabel?form.cityLabel:'所在镇'"
                   @visible-change="visibleChange"
                   @change="cascaderChange"
                   ref="cascader"
                   :key="key">
               </el-cascader>
           </div>

           <div class="operator">
               <el-button size="medium" type="primary" @click="addData">添加表单项</el-button>
           </div>

       </div>
       <div class="d-c-table">
           <el-table
               :data="tableData"
               class="table-box"
               :height="tableHeight"
           >
               <el-table-column
                   fixed
                   prop="date"
                   label="日期"
                   type="index"
                   width="150"
               >
                   <template slot="header">
                       <div class="th-title">表单项标题</div>
                       <div class="th-title">表单项类型</div>
                   </template>
               </el-table-column>


               <template v-for="(item, index) in titleList">
                   <el-table-column
                       :prop="item.prop"
                       :label="`表单类型${index+1}`"
                       min-width="150"
                       :key="`table-column${index}`"
                   >
                       <template slot="header" slot-scope="row">
                           <div class="th-title">
                               <el-input
                                   v-model="row._self.titleList[index].newTitle"
                                   class="w120"
                                   :placeholder="`表单项${index+1}`"
                                   size="mini"
                               ></el-input>
                               <div class="del" v-if="index > limit -1" @click="remove(index)">
                                   <i class="el-icon-delete"></i>
                               </div>
                           </div>
                           <div class="th-title">
                               <el-select
                                   v-model=" row._self.titleList[index].newValueKindId"
                                   size="mini"
                                   placeholder="请选择"
                                   class="w120"
                                   v-if="index > limit - 1"
                               >
                                   <el-option
                                       v-for="item in formTypeEx"
                                       :key="'formType'+item.id"
                                       :label="item.label"
                                       :value="item.id"
                                   >
                                   </el-option>
                               </el-select>
                               <el-select
                                   v-model=" row._self.titleList[index].newValueKindId"
                                   size="mini"
                                   placeholder="请选择"
                                   class="w120"
                                   v-else
                               >
                                   <el-option
                                       v-for="item in formType"
                                       :key="'formType'+item.id"
                                       :label="item.label"
                                       :value="item.id"
                                   >
                                   </el-option>
                               </el-select>
                           </div>
                       </template>


                       <template slot-scope="row">
                           <template v-if="isImg(row, item).flag">
                               <el-image
                                   style="width: 100px; height: 100px"
                                   :src="isImg(row, item).data[0]"
                                   :preview-src-list="isImg(row, item).data">
                               </el-image>
                           </template>
                           <template v-else>
                               {{isImg(row, item).data}}
                           </template>
                       </template>

                   </el-table-column>
               </template>
           </el-table>
       </div>
       <div class="d-c-bottom">
          预览效果仅展示前20行数据
       </div>


       <el-dialog
           :visible.sync="msgVisible"
           custom-class="detail-page-dialog"
           width="40%">
           <p><i class="el-icon-warning"></i>格式有误</p>
           <div class="msg">
             <p>如点击确认将会默认匹配为[单行文本]</p>
             <p v-for="(item, i) in msg" :key="'msg'+ i">  {{item.title}}</p>
           </div>
           <span slot="footer" class="dialog-footer">
    <el-button @click="msgVisible = false">取 消</el-button>
    <el-button type="primary" @click="msgDialogClose">确 定</el-button>
  </span>
       </el-dialog>

       <el-dialog
           title="提示"
           :visible.sync="dialogVisible"
           width="30%">
           <span>确认是否删除</span>
           <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="delConfirm">确 定</el-button>
  </span>
       </el-dialog>


   </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import { State } from "vuex-class";
import { isNone } from "@/utils";

type FormType = {
    id: string;
    value: string;
    label: string;
}
type titleListType = {
    newValueKindId: string;
    newTitle: string;
    prop: string;
}
@Component({
    name: "detailPageNotAlive"
})
export default class DetailPage2 extends Vue {
    @Prop({
        type: Object,
        default() {
            return null;
        }
    })data: any


    @Prop({
        type: Object,
        default() {
            return null;
        }
    })excelAddData: any


    @Prop({
        type: String,
        default: ''
    })formName: string | undefined


    @Prop({
        type: String,
        default: ''
    })excelPath: string | undefined


    @State(state => state.authArea) authArea: any;
    // 当前用户所处层级菜单
    get client() {
        return this.$getUserLevel(this.authArea && this.authArea.orgCategoryId).name;
    }

    get _isOperation() {
        const flag = ['ADMIN', 'OPERATION_ADMIN', 'OPERATION'].includes(this.client);
        if (!flag && localStorage.userInfo) {
            const userInfo = JSON.parse(localStorage.userInfo);
            this.$set(this.form, 'cityCode', [userInfo.cityCode]);
            this.$set(this.form, 'cityCodeLast', userInfo.cityCode);
        }
        return flag;
    }


    @Watch('data', { immediate: true })
    getData(newVal: any) {
        if (isNone(this.excelAddData)) {
            this.titleList = newVal.title.map((item: string, index: number) => {
                return {
                    newValueKindId: '1',
                    newTitle: item,
                    prop: 'titleList' + index
                };
            });
        } else {
            this.titleList = this.excelAddData.list;
            this.form = this.excelAddData.base;
        }
        let tableData = newVal.data.map((item: any) => {
            const res = {};
            for (let i = 0; i < item.length; i++) {
                res['titleList' + i] = item[i];
            }
            return res;
        });
        if (tableData.length > 20) {
            tableData = tableData.splice(0, 20);
        }
        this.tableData = tableData;
        this.limit = newVal.title.length;
    };

    form: any = {
        cityCode: [],
        formName: this.formName,
        formDescription: '',
        excelPath: this.excelPath,
        cityCodeLast: '',
        cityLabel: ''
    }

    props = {
        checkStrictly: true,
        value: 'code',
        label: 'name',
        lazy: true,
        lazyLoad: async(node: any, resolve: any) => {
            if (node.level === 0 || node.data.tier < 4) {
                const res: any = await this.getOptions(node.value);
                res.forEach((item: any) => {
                    item.disabled = item.tier !== 4;
                });
                resolve(res);
            } else {
                resolve([]);
            }
        }
    }


    formType: FormType []= [
        { id: "-1", value: "input-text", label: "所属村" },
        { id: "1", value: "input-text", label: "单行文本" },
        { id: "2", value: "input-textarea", label: "多行文本" },
        { id: "12", value: "input-num", label: "整数" },
        { id: "13", value: "input-num-decimal", label: "小数" },
        { id: "6", value: "select", label: "单选" },
        { id: "7", value: "cascader", label: "多选" },
        { id: "4", value: "location", label: "定位" },
        { id: "3", value: "input-date", label: "日期选择" },
        { id: "5", value: "upload-img", label: "上传图片" },
        { id: "11", value: "input-datetime", label: "日期时间选择" }
    ]

    objType: {
        [key: number]: string;
    } = {
        1: "单行文本",
        2: "多行文本",
        12: "数字",
        13: "小数",
        6: "单选",
        7: "多选",
        4: "定位",
        3: "日期选择",
        5: "上传图片",
        11: "日期时间选择",
        '-1': "所属村"
    }

    formTypeEx: FormType []= [
        { id: "5", value: "upload-img", label: "上传图片" },
        { id: "8", value: "upload-video", label: "上传视频" }
    ]


    selects: unknown[]=[]
    tableData: any[] =[]
    titleList: titleListType[] =[]
    options: any[] = []

    key = 0
    limit = 0
    msgVisible = false
    dialogVisible = false
    removeIndex = 0
    msg: {title: string;index: number}[] = []
    tableHeight = 0


    created() {
        this.$nextTick(() => {
            this.getTableHeight();
            window.addEventListener("resize", this.getTableHeight);
            this.$on('hook:beforeDestroy', () => {
                window.removeEventListener("resize", this.getTableHeight);
            });
        });
    }

    addData() {
        this.titleList.push({
            newValueKindId: '5',
            prop: 'titleList' + this.titleList.length,
            newTitle: ''
        });
    }

    delConfirm() {
        this.titleList.splice(this.removeIndex, 1);
        this.dialogVisible = false;
        this.removeIndex = 0;
    }

    remove(index: number) {
        this.removeIndex = index;
        this.dialogVisible = true;
    }


    async next() {
        if (!this.formValidator()) {
            return false;
        }
        const valueKindIdList = this.titleList.map((item: titleListType) => item.newValueKindId);

        const rs = await this.$server["importCreate/secondVerification"]({
            data: {
                excelPath: this.excelPath,
                valueKindIdList,
                townCityCode: this.form.cityCodeLast
            }
        });
        if (rs.data.code !== 200) {
            this.$message.error(rs.data.message || "接口请求错误!");
            return false;
        }
        if (rs.data.data && rs.data.data.length === 0) {
            this.$emit('success', {
                base: this.form,
                list: this.titleList
            });
            return false;
        }
        if (rs.data.data && rs.data.data.length > 0) {
            this.msg = rs.data.data.map((item: number) => {
                return {
                    title: `${this.titleList[item].newTitle}，${this.objType[this.titleList[item].newValueKindId]}类型数据格式有误`,
                    index: item
                };
            });
            this.msgVisible = true;
        }
    }

    msgDialogClose() {
        const errorArr = this.msg.map((item: {title: string;index: number}) => item.index);
        this.msg = [];
        this.msgVisible = false;

        this.titleList = this.titleList.map((item: titleListType, index: number) => {
            if (errorArr.includes(index)) {
                item.newValueKindId = '1';
            }
            return item;
        });

        this.$emit('success', {
            base: this.form,
            list: this.titleList
        });
    }


    formValidator() {
        let msg = '';
        switch (true) {
        case isNone(this.form.formName):
            msg = '请填写表单名称';
            break;
        case isNone(this.form.cityCodeLast) && this._isOperation:
            msg = '请选择数据对应镇';
            break;
        case this.titleList.some((item: titleListType) => isNone(item.newTitle)):
            msg = '请填写所有的表单项标题';
            break;
        default:
            msg = '';
        }
        if (!isNone(msg)) {
            this.$message.error(msg);
            return false;
        }
        return true;
    }


    async getOptions(code?: any) {
        let list: any[] = [];
        const res = await this.$server["userList/getArea"]({
            data: {
                code: code || ""
            },
            loader: false
        });
        if (res.data.code === 200) {
            list = res.data.data;
        } else {
            this.$message.error(res.data.message || "接口请求错误!");
        }
        return list;
    }


    visibleChange(show: any) {
        if (!show && !this.form.cityCode.length) {
            this.key++;
        }
    }

    cascaderChange() {
        this.$set(this.form, 'cityLabel', (this.$refs.cascader as any).getCheckedNodes()[0].pathLabels.join('/'));
        this.$set(this.form, 'cityCodeLast', this.form.cityCode[this.form.cityCode.length - 1]);
        if (!this.form.cityCode.length) {
            this.key++;
        }
    }


    getTableHeight() {
        this.$nextTick(() => {
            try {
                const table = document.querySelector('.d-c-table');
                if (table) {
                    const tableTop = table.getBoundingClientRect().top; // table距离顶部的高度
                    this.tableHeight = window.innerHeight - tableTop - 70;
                }
            } catch (e) {
                console.log(e);
            }
        });
    }


    isImg(row: any, item: any) {
        const flag = /\/temporary\/img/g.test(row.row[item.prop]);
        let data = row.row[item.prop];
        if (flag) {
            data = JSON.parse(data);
            data = data.map((val: any) => this.$staticUrl + val);
        }
        return {
            flag,
            data
        };
    }
}
</script>

<style scoped lang="scss">
.detail-page-dialog{
    p{
        font-size: 16px;
        color: rgba(0, 0, 0, 0.85);
        display: flex;
        align-items: center;
        i{
            font-size: 20px;
            color: #E6A23C;
            margin-right: 5px;
        }
    }
    .msg{
        font-weight: 400;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.65);
        line-height: 22px;
        padding-left: 25px;
        padding-right: 75px;
        max-height: 400px;
        overflow-y: auto;
        overflow-x: hidden;
    }
}

.detailPage2-container{
    display: flex;
    flex-direction: column;
    height: 100%;
    ::v-deep{
        table{
            width: 100%;
        }
        .el-table th{
            background: #F7F7F7;
            line-height: 22px;

            font-size: 14px;
            font-weight: bold;
            color: #37383a;
        }
        .el-table th .th-title{
            line-height: 22px;
            padding: 10px 0;
            display: flex;
            align-items: center;
            i{
                cursor: pointer;
                color: rgb(16, 16, 16);
                padding-left: 5px;
            }
        }
        .el-table__body-wrapper{
            height: auto;
        }
    }

    .d-c-top{
        display: flex;
        height: 56px;
        position: relative;
        .d-c-form{
            display: flex;
            align-items: center;
            padding: 10px 20px;
        }
        .form-label{
            font-size: 14px;
            color: #37383a;
            padding-right: 10px;
        }
        .form-label.required::before{
            content: "*";
            color: #de2728;
            margin-right: 4px;
        }
        .form-input{
            width: 220px;
        }
        .operator{
            display: flex;
            align-items: center;
            position: absolute;
            right: 10px;
            height: 100%;
        }
    }

    .d-c-table{
        display: flex;
        flex: 1;
        background-color: #EDEFF2;
        .table-box{
            flex: 1;
            overflow: auto;
        }
    }
    .d-c-bottom{
        height: 45px;
        display: flex;
        align-items: center;
        padding-left: 20px;
        font-size: 14px;
    }
    .w120{
        width: 120px;
    }
}

</style>
